//一、引入内置/第三方模块
var express = require('express');  		 //express框架
var fs = require("fs");			   		 //文件处理模块
var path = require("path");		   		 //路径处理模块
var bodyParser = require('body-parser'); //解析POST请求数据

//二、创建服务器
var app = express(); 

//三、配置  

	app.use(express.static('public'))

	//3.1 允许跨域和相应数据格式
	app.all('/api/*', function(req, res, next) {
		console.log(req.url)
		res.header("Access-Control-Allow-Origin", "*")
		res.header("Access-Control-Allow-Headers", "Content-Type, X-Requested-With, Authorization, mytoken")
		res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
		res.setHeader('Content-Type','application/json;charset=utf-8')
		if(req.method=="OPTIONS") res.send(200);//让options请求快速返回
		else  next()
	});

	//3.2 数据过滤（将POST请求数据解析后放到req对象的body属性中）
	app.use(bodyParser.json()); //解析JSON格式数据（application/json） 
	app.use(bodyParser.urlencoded({ extended: false })); //解析文本格式数据（application/x-www-form-urlencoded）

	//3.3 初始化数据库模块
	var database = require('./application/database');
	database.initialize(app, function(err) {
		if(err) {
			console.error("连接数据库失败失败 %s", err);
		} 
	});
  
//四、路由
	// 项目全局使用方法
	app.use(require('./application/common'));

  	// 登录&身份校验
	const adminLogin = require(path.join(process.cwd(), "application/routes/api/login"));
	app.use("/api/private/v1/login", adminLogin.login);
	app.use("/api/private/v1/*",     adminLogin.tokenAuth);
  	// 根据路径来自动加载路由
	var mount = require('mount-routes');
	mount(app, "./application/routes")

	// 权限验证
	var authorization = require(path.join(process.cwd(),"application/routes/api/authorization"));
	var roleService = require(path.join(process.cwd(),"application/services/RoleService"));
	// 设置全局权限
	authorization.setAuthFn(function(req,res,next,serviceName,actionName,passFn) {
		if(!req.userInfo || isNaN(parseInt(req.userInfo.rid))) return res.sendResult("无角色ID分配");
		// 验证权限
		roleService.authRight(req.userInfo.rid,serviceName,actionName,function(err,pass) {
			passFn(pass);
		});
	});

	// 404（Express中间件 路由匹配不上触发）
	app.use(function(req, res, next) {
		res.sendJson(404, "Not Found", null);
	});

//四、启动服务
app.listen(8888, function(){
	console.log('接口项目启动成功，测试：http://localhost:8888/路径')
});



